/**
 * Created by taoyouyou on 2018/7/17.
 */
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from './store'

import layout from './pages/layout.vue'
import index from './pages/index.vue'

Vue.use(VueRouter)

function load (component) {
  return () => System.import(`./pages/${component}.vue`)
}

const router = new VueRouter({
  mode: 'hash',
  routes: [
    {
      path: '/',
      component: layout,
      meta: {requireAuth: true},
      children: [
        {path: '', component: index}
      ]
    },
    {
      path: '/login',
      component: load('login'),
      meta: {requireAuth: false}
    },
    {
      path: '/register',
      component: load('register'),
      meta: {requireAuth: false}
    },
    {
      path: '*',
      component: layout,
      meta: {requireAuth: false}
    },
    {
      path: '/test',
      component: load('test'),
      meta: {requireAuth: false}
    },
    {
      path: '/store',
      component: layout,
      meta: {requireAuth: false},
      children: [
        {path: 'list', name: '店铺设置', component: load('store')},
      ]
    },
    {
      path: '/seat',
      component: layout,
      meta: {requireAuth: false},
      children: [
        {path: 'category', name: '类型设置', component: load('seat/category')},
        {path: 'table', name: '桌位设置', component: load('seat/table')},
        {path: 'setting', name: '排座', component: load('setSeat')},
      ]
    }
  ]
})

router.beforeEach((to, from, next) => {
  if (to.matched.some(r => r.meta.requireAuth)) {
    if (store.state.token) {
      next()
    } else {
      next({
        path: '/login',
        query: {redirect: to.fullPath}
      })
    }
  } else {
    next()
  }
})

export default router
